package com.vrv.app.cyberspace.modules.sys.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.vrv.app.cyberspace.common.ddio.ApiV2Service;
import com.vrv.app.cyberspace.common.ddio.DDIORunnable;
import com.vrv.app.cyberspace.common.ddio.TemplateMessage;
import com.vrv.app.cyberspace.common.utils.HttpContextUtils;
import com.vrv.app.cyberspace.common.utils.JSONResult;
import com.vrv.app.cyberspace.config.WXBSystemConfig;
import com.vrv.app.cyberspace.modules.sys.entity.RiskApprovalTable;
import com.vrv.app.cyberspace.modules.sys.entity.RiskManageTable;
import com.vrv.app.cyberspace.modules.sys.entity.RoleTable;
import com.vrv.app.cyberspace.modules.sys.entity.UserTable;
import com.vrv.app.cyberspace.modules.sys.mapper.*;
import com.vrv.app.cyberspace.modules.sys.service.IRiskApprovalTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.vrv.app.cyberspace.common.utils.JSONResult.renderError;
import static com.vrv.app.cyberspace.common.utils.JSONResult.renderSuccess;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sm
 * @since 2017-12-25
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
@Transactional
public class RiskApprovalTableServiceImpl extends ServiceImpl<RiskApprovalTableMapper, RiskApprovalTable> implements IRiskApprovalTableService {
    Logger logger = LoggerFactory.getLogger(RiskTableServiceImpl.class);

    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    @Autowired
    private RiskManageTableMapper riskManageTableMapper;
    @Autowired
    private RiskTypeTableMapper riskTypeTableMapper;
    @Autowired
    private RoleTableMapper roleTableMapper;
    @Autowired
    private UserTableMapper userTableMapper;
    @Autowired
    private ApiV2Service apiV2Service;
    @Autowired
    private WXBSystemConfig wxbSystemConfig;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    //同意操作，风险状态为1等待审批的时候可进行此操作
    @Override
    public JSONResult endRiskApproval(Integer id, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        if (roleTable.getRoleRank().equals("6")){
            return renderError("操作被禁止，专家只能进行退回操作！");
        }
        RiskManageTable rmt = riskManageTableMapper.selectById(id);
        if (rmt.getStatus()==4){
            return renderError("操作被禁止，此风险已审批完成!");
        }
        if (!rmt.getApprovalUserID().equals(userTable.getLinkdoodID())){
            return renderError("操作被禁止，当前用户非审批人！");
        }
        //新增审批流程状态7领导同意
        Date now = new Date();
        RiskApprovalTable newrat1 = new RiskApprovalTable();
        newrat1.setBaseID(id);
        newrat1.setUserID(userTable.getLinkdoodID());
        newrat1.setApprovalStatue(7);
        newrat1.setCreateTime(now);
        newrat1.setAdvice(advice);
        newrat1.insert();
/*        //新增审批流程状态 8.等待下发或归档
        RiskApprovalTable newrat2 = new RiskApprovalTable();
        newrat2.setBaseID(id);
        newrat2.setUserID(null);
        newrat2.setApprovalStatue(8);
        newrat2.setCreateTime(now);
        newrat1.setAdvice(null);
        newrat2.insert();*/
        //更改风险状态为审批通过，等待下发或者归档
        rmt.setStatus(4);
        rmt.setUpdateTime(now);
        rmt.setApprovalUserID(rmt.getCreateUserID());
        rmt.updateById();
        logger.info("风险管理审批"+rmt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"审批同意");
        return renderSuccess();
    }

    //退回操作，风险状态为1等待审批的时候可进行此操作
    @Override
    public JSONResult backRiskApproval(Integer id, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        RiskManageTable rmt = riskManageTableMapper.selectById(id);
        if (rmt.getStatus()==4){
            return renderError("操作被禁止，此风险已审批完成!");
        }
        if (!rmt.getApprovalUserID().equals(userTable.getLinkdoodID())){
            return renderError("操作被禁止，当前用户非审批人！");
        }
        //新增审批流程状态
        Date now = new Date();
        RiskApprovalTable newrat1 = new RiskApprovalTable();
        newrat1.setBaseID(id);
        newrat1.setUserID(userTable.getLinkdoodID());
        //如果操作人为专家状态则为4研判完毕，否则为3.领导退回
        if ("6".equals(roleTable.getRoleRank())){
            newrat1.setApprovalStatue(4);
        }else {
            newrat1.setApprovalStatue(3);
        }
        newrat1.setCreateTime(now);
        newrat1.setAdvice(advice);
        newrat1.insert();
/*        //新增审批流程状态5值班员审核中
        RiskApprovalTable newrat2 = new RiskApprovalTable();
        newrat2.setBaseID(id);
        newrat2.setUserID(null);
        newrat2.setApprovalStatue(5);
        newrat2.setCreateTime(now);
        newrat1.setAdvice(null);
        newrat2.insert();*/
        //更改风险状态为值班员审批，等待值班员重新请示领导
        rmt.setStatus(1);
        rmt.setUpdateTime(now);
        rmt.setApprovalUserID(rmt.getCreateUserID());
        rmt.updateById();
        logger.info("风险管理审批"+rmt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"审批退回");
        pushTemplateMessage(rmt, rmt.getCreateUserID(),riskTypeTableMapper.selectById(rmt.getPrimaryRiskType()).getName());
        return renderSuccess();
    }

    // 转批操作，风险状态为1等待审批的时候可进行此操作
    @Override
    public JSONResult addRiskApproval(Integer id, String advice, String approvalUserID) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        UserTable approvalUser = userTableMapper.selectById(approvalUserID);
        RoleTable approvalUserRole = roleTableMapper.selectById(approvalUser.getRoleID());
        if (!roleTable.getRoleRank().equals("2")){
            if (approvalUserRole.getRoleRank().equals("6")){
                return renderError("操作被禁止，只有值班员才能进行研判！");
            }
        }
        if (roleTable.getRoleRank().equals("6")){
            return renderError("操作被禁止，专家只能进行退回操作！");
        }
        RiskManageTable rmt = riskManageTableMapper.selectById(id);
        if (rmt.getStatus()==4){
            return renderError("操作被禁止，此风险已审批完成!");
        }
        if (!rmt.getApprovalUserID().equals(userTable.getLinkdoodID())){
            return renderError("操作被禁止，当前用户非审批人！");
        }
        //新增审批流程状态，如果请示人为专家状态则为2专家研判，否则为6请示上级领导
        Date now = new Date();
        RiskApprovalTable newrat1 = new RiskApprovalTable();
        newrat1.setBaseID(id);
        newrat1.setUserID(userTable.getLinkdoodID());
        if (approvalUserRole.getRoleRank().equals("6")) {
            newrat1.setApprovalStatue(2);
        }else {
            newrat1.setApprovalStatue(6);
        }
        newrat1.setCreateTime(now);
        newrat1.setAdvice(advice);
        newrat1.insert();
/*        //新增审批流程状态，如果请示人为专家状态则为2专家研判中，否则为1领导审批中
        RiskApprovalTable newrat2 = new RiskApprovalTable();
        newrat2.setBaseID(id);
        newrat2.setUserID(null);
        if (approvalUserRole.getRoleRank().equals("6")) {
            newrat2.setApprovalStatue(2);
        } else {
            newrat2.setApprovalStatue(1);
        }
        newrat2.setCreateTime(now);
        newrat2.setAdvice(null);
        newrat2.insert();*/
        //更改风险状态为领导审批，等待领导审批
        rmt.setStatus(2);
        rmt.setUpdateTime(now);
        rmt.setApprovalUserID(approvalUserID);
        rmt.updateById();
        logger.info("风险管理审批"+rmt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"转批，转批人为："+ approvalUserID);
        pushTemplateMessage(rmt, approvalUserID,riskTypeTableMapper.selectById(rmt.getPrimaryRiskType()).getName());
        return renderSuccess();
    }

    // 归档操作，风险状态如果等于2审批完成或者4下发完成的时候可进行此操作
    @Override
    public JSONResult archiveRiskApproval(Integer id, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        RiskManageTable rmt = riskManageTableMapper.selectById(id);
        if (rmt.getStatus()==7){
            return renderError("操作被禁止，此风险已归档!");
        }
        if (!roleTable.getRoleType().equals("ROLE_DUTY")){
            return renderError("操作被禁止，非值班员无法归档！");
        }
        //新增审批流程状态13归档完毕
        Date now = new Date();
        RiskApprovalTable newrat = new RiskApprovalTable();
        newrat.setBaseID(id);
        newrat.setUserID(userTable.getLinkdoodID());
        newrat.setApprovalStatue(13);
        newrat.setCreateTime(now);
        newrat.setAdvice(null);
        newrat.insert();
        //更改风险状态为已归档
        rmt.setStatus(7);
        rmt.setSummary(advice);
        rmt.setUpdateTime(now);
        rmt.updateById();
        logger.info("风险管理审批"+rmt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"归档");
        return renderSuccess();
    }

    // 下发操作，风险状态如果等于2审批完成的时候可进行此操作
    @Override
    public JSONResult releaseRiskApproval(Integer id, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RiskManageTable rmt = riskManageTableMapper.selectById(id);
        if (rmt.getStatus()==5){
            return renderError("操作被禁止，此风险已进行下发操作!");
        }
        if (!rmt.getApprovalUserID().equals(userTable.getLinkdoodID())){
            return renderError("操作被禁止，当前用户非审批人！");
        }
        //新增审批流程状态9已下发
        Date now = new Date();
/*        RiskApprovalTable newrat1 = new RiskApprovalTable();
        newrat1.setBaseID(id);
        newrat1.setUserID(userTable.getLinkdoodID());
        newrat1.setApprovalStatue(9);
        newrat1.setCreateTime(now);
        newrat1.setAdvice(advice);
        newrat1.insert();*/
/*        //新增审批流程状态10反馈中
        RiskApprovalTable newrat2 = new RiskApprovalTable();
        newrat2.setBaseID(id);
        newrat2.setUserID(null);
        newrat2.setApprovalStatue(10);
        newrat2.setCreateTime(now);
        newrat2.setAdvice(null);
        newrat2.insert();*/
        //更改风险状态为下发中
        rmt.setStatus(5);
        rmt.setUpdateTime(now);
        rmt.setApprovalUserID(rmt.getCreateUserID());
        rmt.updateById();
        logger.info("风险管理审批"+rmt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"下发");
        pushTemplateMessage(rmt, rmt.getCreateUserID(),riskTypeTableMapper.selectById(rmt.getPrimaryRiskType()).getName());
        return renderSuccess();
    }

    // 反馈操作，风险状态如果等于3下发中的时候可进行此操作
    @Override
    public JSONResult feedbackRiskApproval(Integer id, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RiskManageTable rmt = riskManageTableMapper.selectById(id);
        if (rmt.getStatus()==6){
            return renderError("操作被禁止，此风险已反馈完毕!");
        }
        if (!rmt.getApprovalUserID().equals(userTable.getLinkdoodID())){
            return renderError("操作被禁止，当前用户非审批人！");
        }
        //更改旧审批流程状态11反馈完毕
        Date now = new Date();
/*        RiskApprovalTable newrat1 = new RiskApprovalTable();
        newrat1.setBaseID(id);
        newrat1.setUserID(userTable.getLinkdoodID());
        newrat1.setApprovalStatue(11);
        newrat1.setCreateTime(now);
        newrat1.setAdvice(advice);
        newrat1.insert();*/
/*        //新增审批流程状态12等待归档中
        RiskApprovalTable newrat2 = new RiskApprovalTable();
        newrat2.setBaseID(id);
        newrat2.setUserID(null);
        newrat2.setApprovalStatue(12);
        newrat2.setCreateTime(now);
        newrat2.setAdvice(null);
        newrat2.insert();*/
        //更改风险状态为下发完成（反馈完毕）
        rmt.setStatus(6);
        rmt.setUpdateTime(now);
        rmt.setApprovalUserID(rmt.getCreateUserID());
        rmt.updateById();
        logger.info("风险管理审批"+rmt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"反馈完毕");
        pushTemplateMessage(rmt, rmt.getCreateUserID(),riskTypeTableMapper.selectById(rmt.getPrimaryRiskType()).getName());
        return renderSuccess();
    }

    private void pushTemplateMessage(RiskManageTable rmt, String toUsers,String type) {
        String appid = apiV2Service.getAppID();
        String content = "时间: " + dateFormat.format(new Date()) + "\n标题：" + rmt.getTitle() + "\n类别: " + type + "\n请您及时处理 ";
        TemplateMessage templateMessage = TemplateMessage.createOne(appid, "风险管理", appid, content, wxbSystemConfig.getRiskFeedbackDetailUrl() + "&id=" + rmt.getBaseID(),
                toUsers);
        try {
            executorService.execute(new DDIORunnable(apiV2Service, "sendTemplateMsg", templateMessage, TemplateMessage.class));
        } catch (NoSuchMethodException e) {
            logger.info("推送风险管理"+"(ID" + rmt.getBaseID() + ")消息失败! ");
            e.printStackTrace();
        }
    }
}
